package com.zhilianbao.leyaogo.ui.adapter.me;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bql.baseadapter.recycleView.QuickRcvAdapter;
import com.bql.baseadapter.recycleView.QuickRcvHolder;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.model.response.me.MyOrderResponse;
import com.zhilianbao.leyaogo.ui.activity.me.ServiceAndHelpActivity;
import com.zhilianbao.leyaogo.ui.activity.me.myorder.OrderDetailActivity;
import com.zhilianbao.leyaogo.ui.fragment.me.myorder.BaseOrderFragment;
import com.zhilianbao.leyaogo.utils.ImageUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.dialog.CommonDialog;
import com.zhilianbao.leyaogo.view.me.MyOrderHorizontalListView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import okhttp3.Call;
import okhttp3.Response;


/**
 * 我的订单adapter
 */
public class MyOrderAdapter extends QuickRcvAdapter<MyOrderResponse> {

    private LinearLayout mOrderDetail;
    private TextView mOrderState;
    private TextView mGoodsDetail;
    private Context mContext;
    private List<MyOrderResponse> mList;
    private TextView mItemOrderNum;
    private MyOrderHorizontalListView mHorizontalListView;
    private ImageView mGoodsIcon;
    private TextView mGoodsTotalPrice;
//    private double totalPrice;
    private TextView mGoodsNum;
    private LinearLayout mLlHorizontal;
    private TextView mGoodsCount;
    private int mMyOrderType;
//    private MoneyTextView mGoodsUnitPrice;
    private CommonDialog mCommonDialog;
    private BaseOrderFragment mBaseOrderFragment;

    public MyOrderAdapter(BaseOrderFragment baseOrderFragment, Context context, List<MyOrderResponse> list, int currentChild) {
        super(context, list, R.layout.item_order);
        this.mList = list;
        this.mContext = context;
        this.mMyOrderType = currentChild;
        this.mBaseOrderFragment = baseOrderFragment;
    }

    @Override
    protected void bindDataHelper(QuickRcvHolder quickRcvHolder, int position, MyOrderResponse myOrderResponse) {
        TextView orderCancel = quickRcvHolder.getView(R.id.order_cancel);
        TextView orderPayNow = quickRcvHolder.getView(R.id.order_pay_now);
        findView(quickRcvHolder);
        setData(position, myOrderResponse, orderCancel, orderPayNow);
    }

    private void findView(QuickRcvHolder quickRcvHolder) {
        mOrderDetail = quickRcvHolder.getView(R.id.order_detail);
        mOrderState = quickRcvHolder.getView(R.id.item_order_state);
        mGoodsDetail = quickRcvHolder.getView(R.id.goods_detail);
        mItemOrderNum = quickRcvHolder.getView(R.id.item_order_num);
        mHorizontalListView = quickRcvHolder.getView(R.id.hl_list_view);
        mGoodsIcon = quickRcvHolder.getView(R.id.goods_icon);
        mGoodsTotalPrice = quickRcvHolder.getView(R.id.goods_total_price);
        mGoodsNum = quickRcvHolder.getView(R.id.goods_num);
//        mGoodsUnitPrice = quickRcvHolder.getView(R.id.goods_unit_price);
        mGoodsCount = quickRcvHolder.getView(R.id.goods_count);
        mLlHorizontal = quickRcvHolder.getView(R.id.ll_horizontal);
    }

    public void setData(int position, MyOrderResponse myOrderResponse, TextView orderCancel, TextView orderPayNow) {

        int orderCode = myOrderResponse.getOrderCode();
        List<MyOrderResponse.OrderItemBean> orderItem = myOrderResponse.getOrderItem();

        if (orderItem == null || orderItem.size() == 0) {
            mOrderDetail.setVisibility(View.GONE);
            mLlHorizontal.setVisibility(View.GONE);
//            totalPrice = 0;
        } else if (orderItem.size() == 1) {//一个商品,正常显示
            mOrderDetail.setVisibility(View.VISIBLE);
            mLlHorizontal.setVisibility(View.GONE);
            MyOrderResponse.OrderItemBean orderItemBean = myOrderResponse.getOrderItem().get(0);
            String goodsTitle = orderItemBean.getGoodsName();
            ImageUtils.loadGoodsPic(Utils.returnUrlShow(orderItemBean.getGoodsPic()), mGoodsIcon);
//            totalPrice = orderItemBean.getAmountPrice();
            mGoodsDetail.setText(goodsTitle);
//            mGoodsUnitPrice.setAmount(orderItemBean.getAmountPrice());
//            if (orderItemBean.getUnit() != null) {
//                mGoodsCount.setText("/" + orderItemBean.getUnit());
//            }else {
//                mGoodsCount.setText("");
//            }
            mGoodsCount.setText(orderItemBean.getGoodsDesc());
            mGoodsNum.setText("x " + orderItemBean.getNumber());
        } else {//多个商品,显示横向图片展示
            mOrderDetail.setVisibility(View.GONE);
            mHorizontalListView.setVisibility(View.VISIBLE);
            OrderHorizontalListAdapter orderHorizontalListAdapter = new OrderHorizontalListAdapter(mContext, orderItem);
            mHorizontalListView.setAdapter(orderHorizontalListAdapter);
            mHorizontalListView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    intoOrderDetail(position);
                }
            });
            mLlHorizontal.setVisibility(View.VISIBLE);
//            totalPrice = 0;
//            for (int i = 0; i < orderItem.size(); i++) {
//                MyOrderResponse.OrderItemBean orderItemBean = orderItem.get(i);
//                totalPrice = NumberUtlis.add(totalPrice, orderItemBean.getTotalPrice());
//            }
        }
//        double totalAndPostPrice = NumberUtlis.add(totalPrice, myOrderResponse.getPostPrice());
        //设置高亮字体
        Utils.highlightStr(mGoodsTotalPrice, "共" + orderItem.size() + "个商品 合计 ：  ¥ " + myOrderResponse.getPaymentPrice() + "（含运费¥" + myOrderResponse.getPostPrice() + "）", "¥ " + myOrderResponse.getPaymentPrice(), mContext.getResources().getColor(R.color.color_f91c4c));
        mItemOrderNum.setText("订单编号:" + myOrderResponse.getOrderNo());
        setButtonShow(orderCode, position, orderCancel, orderPayNow);

    }


    private void setButtonShow(int orderCode, int position, TextView orderCancel, TextView orderPayNow) {
        switch (orderCode) {
            case 1://待确认
            case 2://已确认
            case 3://未支付(暂时都统一为待支付)
                mOrderState.setText("待付款");
                setButtonVisible(orderCancel, orderPayNow, View.VISIBLE, View.VISIBLE);
                setButtonText(orderCancel, orderPayNow, "取消订单", "立即支付");
                break;
            case 4://已支付
                mOrderState.setText("待发货");
                setButtonVisible(orderCancel, orderPayNow, View.GONE, View.VISIBLE);
                setButtonText(orderCancel, orderPayNow, null, "申请售后");
                break;
            case 5://已发货
                mOrderState.setText("待收货");
                setButtonVisible(orderCancel, orderPayNow, View.GONE, View.VISIBLE);
                setButtonText(orderCancel, orderPayNow, null, "确认收货");
                break;
            case 6://已完成
                mOrderState.setText("已完成");
                setButtonVisible(orderCancel, orderPayNow, View.GONE, View.VISIBLE);
                setButtonText(orderCancel, orderPayNow, null, "申请售后");
                break;
            case 99://已取消
                mOrderState.setText("已取消");
                setButtonVisible(orderCancel, orderPayNow, View.GONE, View.VISIBLE);
                setButtonText(orderCancel, orderPayNow, null, "删除订单");
                break;
        }
        initOnclick(position, orderCancel, orderPayNow);
    }

    //设置2个按钮的文字
    private void setButtonText(TextView orderCancel, TextView orderPayNow, String s1, String s2) {
        orderCancel.setText(s1);
        orderPayNow.setText(s2);
    }

    //按顺序2个按钮,最后一个为红色,参数传入显示或消失
    private void setButtonVisible(TextView orderCancel, TextView orderPayNow, int a, int b) {
        orderCancel.setVisibility(a);
        orderPayNow.setVisibility(b);
    }


    private void initOnclick(int position, TextView orderCancel, TextView orderPayNow) {
        orderPayNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = orderPayNow.getText().toString().trim();
                if ("删除订单".equals(string)) {
                    showDelDialog(position);
                } else if ("取消订单".equals(string)) {
                    showCancelDialog(position, orderCancel, orderPayNow);
                } else if ("立即支付".equals(string)) {
                    //进入订单详情
                    intoOrderDetail(position);
                } else if ("确认收货".equals(string)) {
                    showSureReceiveDialog(position, orderCancel, orderPayNow);
                } else if ("申请售后".equals(string)) {
                    //进入客服与帮助页面
                    Utils.startActivity((Activity) mContext, ServiceAndHelpActivity.class);
                }
            }
        });
        orderCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String cancel = orderCancel.getText().toString().trim();
                if ("取消订单".equals(cancel)) {
                    showCancelDialog(position, orderCancel, orderPayNow);
                }
            }
        });
        mOrderDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intoOrderDetail(position);
            }
        });
    }


    //进入订单详情页
    private void intoOrderDetail(int position) {
        MyOrderResponse myOrderResponse = mList.get(position);
        Intent intent = new Intent(mContext, OrderDetailActivity.class);
        intent.putExtra("userId", myOrderResponse.getUserId());
        intent.putExtra("orderId", myOrderResponse.getOrderId());
        intent.putExtra("position", position);

        mContext.startActivity(intent);
    }

    /**
     * 删除提示框
     */
    private void showDelDialog(int position) {
        mCommonDialog = CommonDialog.createTwoButton(mContext.getString(R.string.confirm), mContext.getString(R.string.cancel), "删除后无法恢复,确定要删除吗?");
        mCommonDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                long orderId = mList.get(position).getOrderId();
                long userId = mList.get(position).getUserId();
                int type = 0;
                AccountApi.setOrder(mContext, orderId, userId, type, new DialogCallback<Object>(mContext) {
                    @Override
                    public void onSuccess(Object o, Call call, Response response) {
                        mList.remove(position);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(position, mList.size());
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ORDER_ITEM_DELETE, mMyOrderType));
                    }
                });
                mCommonDialog.dismiss();
            }

            @Override
            public void right() {
                mCommonDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        mCommonDialog.show(mBaseOrderFragment.getFragmentManager(), "delete");
    }

    /**
     * 取消提示框
     */
    private void showCancelDialog(int position, TextView orderCancel, TextView orderPayNow) {
        mCommonDialog = CommonDialog.createTwoButton(mContext.getString(R.string.confirm), mContext.getString(R.string.cancel), "确定取消订单吗?");
        mCommonDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                //订单由待支付状态变为已取消状态或者由待发货状态变为已取消状态
                MyOrderResponse myOrderResponse = mList.get(position);
                long orderId = myOrderResponse.getOrderId();
                long userId = myOrderResponse.getUserId();
                int type = 1;
                AccountApi.setOrder(mContext, orderId, userId, type, new DialogCallback<Object>(mContext) {
                    @Override
                    public void onSuccess(Object o, Call call, Response response) {
//                            myOrderResponse.setOrderCode(99);
                        if (mMyOrderType != 0) {
                            mList.remove(position);
                            notifyItemRemoved(position);
                            notifyItemRangeChanged(position, mList.size());
                        }
                        mOrderState.setText("已取消");
                        setButtonVisible(orderCancel, orderPayNow, View.GONE, View.VISIBLE);
                        setButtonText(orderCancel, orderPayNow, null, "删除订单");
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ORDER_CANCEL, mMyOrderType));
                    }
                });
                mCommonDialog.dismiss();
            }

            @Override
            public void right() {
                mCommonDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        mCommonDialog.show(mBaseOrderFragment.getFragmentManager(), "cancel");
    }

    /**
     * 确认收货提示框
     */
    private void showSureReceiveDialog(int position, TextView orderCancel, TextView orderPayNow) {
        mCommonDialog = CommonDialog.createTwoButton(mContext.getString(R.string.confirm), mContext.getString(R.string.cancel), "确认收货后,资金将转入卖家,确认收货吗?");
        mCommonDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                MyOrderResponse myOrderResponse = mList.get(position);
                long orderId = myOrderResponse.getOrderId();
                long userId = myOrderResponse.getUserId();
                int type = 2;
                AccountApi.setOrder(mContext, orderId, userId, type, new DialogCallback<Object>(mContext) {
                    @Override
                    public void onSuccess(Object o, Call call, Response response) {
                        if (mMyOrderType != 0) {
                            mList.remove(position);
                            notifyItemRemoved(position);
                            notifyItemRangeChanged(position, mList.size());
                        }
                        XToastUtils.showShortToast("收货完成");
                        mOrderState.setText("已完成");
                        setButtonVisible(orderCancel, orderPayNow, View.GONE, View.VISIBLE);
                        setButtonText(orderCancel, orderPayNow, null, "申请售后");
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SURE_RECEIVE, mMyOrderType));
                    }
                });
                mCommonDialog.dismiss();
            }

            @Override
            public void right() {
                mCommonDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        mCommonDialog.show(mBaseOrderFragment.getFragmentManager(), "sure_receive");
    }
}

